package com.dongdongshop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.dongdongshop.api.OrderServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.service.AliPayService;
import com.dongdongshop.vo.AliPayQueryRefundVO;
import com.dongdongshop.vo.AlipayTradeRefundVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class AliPayServiceImpl implements AliPayService {
    @Autowired
    private AlipayClient alipayClient;

    @Value("${alipay.NotifyUrl}")
    private String NotifyUrl;

    @Value("${alipay.ReturnUrl}")
    private String ReturnUrl;

    @Autowired
    private OrderServiceApi orderServiceApi;

    @Override
    public String tradePay(String out_trade_no, String total_amount, String subject) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //异步回调接口 : 支付宝通知我们的接口,支付是否成功
        request.setNotifyUrl(NotifyUrl);
        //同步回调接口: 让用户从付款页调回我们的页面的
        request.setReturnUrl(ReturnUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", subject);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }

    @Override
    public Result queryTrade(String out_trade_no, String trade_no) {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("trade_no", trade_no);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.FAIL();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        //查询出来的结果在这里
        String body = response.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        return Result.OK().setData(jsonObject);
    }

    @Override
    public Result tradeRefund(String trade_no, String refund_amount, String out_request_no, Long id) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", trade_no);
        bizContent.put("refund_amount", refund_amount);
        bizContent.put("out_request_no", out_request_no);
        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return Result.FAIL();
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            AlipayTradeRefundVO alipayTradeRefundVO = jsonObject.parseObject(jsonObject.toJSONString(jsonObject.get("alipay_trade_refund_response")), AlipayTradeRefundVO.class);
            if (!Objects.equals(alipayTradeRefundVO.getFund_change(), "Y")) {
                //退款失败  1.重复退款
                //2.失败
                AliPayQueryRefundVO aliPayQueryRefundVO = queryRefund(trade_no, out_request_no);
                if (!Objects.equals(aliPayQueryRefundVO.getRefund_status(), "REFUND_SUCCESS")) {
                    return Result.FAIL().setData("退款失败");
                }
                return Result.FAIL().setData("已经退款,请勿重复操作");
            }
            orderServiceApi.refundOrderStatus(id);
            return Result.OK().setData("退款成功");
        } else {
            System.out.println("调用失败");
            return Result.FAIL().setData("退款失败");
        }
    }

    private AliPayQueryRefundVO queryRefund(String trade_no, String out_request_no) {
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", trade_no);
        bizContent.put("out_request_no", out_request_no);
        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return null;
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            AliPayQueryRefundVO refundQuery = jsonObject.parseObject(jsonObject.toJSONString(jsonObject.get("alipay_trade_fastpay_refund_query_response")), AliPayQueryRefundVO.class);
            return refundQuery;
        } else {
            System.out.println("调用失败");
            return null;
        }
    }
}
